<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img :src="img" alt="" class="preview" v-if="img"/>
      <img src="../../../assets/images/avatar.jpg" alt="" class="preview" v-else/>

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input type="file" style="display:none" ref="iptfileRef" accept="image/*" @change="onFileChange">
        <el-button type="primary" icon="el-icon-plus" @click="chooseImage">选择图片</el-button>
        <el-button type="success" icon="el-icon-upload" :disabled="img===''"
          @click="upload">上传头像</el-button
        >
      </div>
    </div>
  </el-card>
</template>

<script>
import { avatarAPI } from '@/api/user.js'
export default {
  name: 'UserAvatar',
  data () {
    return {
      img: ''
    }
  },
  methods: {
    chooseImage () {
      this.$refs.iptfileRef.click()
    },
    onFileChange (e) {
      const files = e.target.files
      if (files.length === 0) {
        // 没有选中文件
      } else {
        // 选中了文件
        const fr = new FileReader()
        fr.readAsDataURL(files[0])
        fr.onload = () => {
          this.img = fr.result
        }
      }
    },
    async upload () {
      if (!this.img) return
      const { data: res } = await avatarAPI(this.img)
      console.log(res)
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.$store.dispatch('user/initUser')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
  width: 350px;
  height: 350px;
}
</style>
